<template>
    <div class="main-bottomer-container" >
        <div class="cover-img">
            <img :src="songMsg.coverImg" @click="showPlayer" @mouseenter="isShowOpen=true" @mouseleave="isShowOpen=false">
            <img v-if="isShowOpen" style="opacity: 0.7; pointer-events: none" src="../../assets/main/bottem/open.jpg">
        </div>
        <div class="player-view">
            <img src="../../assets/main/player/pre.png" class="btn" @click="playPre">
            <div style="width: 20px"></div>
            <img v-if="!isPlay" src="../../assets/main/player/play.png" class="btn" @click="playOrPause">
            <img v-if="isPlay" src="../../assets/main/player/purse.png" class="btn" @click="playOrPause">
            <div style="width: 20px"></div>
            <img src="../../assets/main/player/next.png" class="btn" @click="playNext">
            <div style="width: 40px"></div>
            <div class="slide-box">
                <div class="msg">
                    <div>
                        {{songMsg.name}}-
                        <span v-for="item of songMsg.arts" :key="item">{{item.name}}</span>
                    </div>
                    <div>{{secToMin(currentTime)}}/{{secToMin(totalTime)}}</div>
                </div>
                <div class="slide">
                    <van-slider v-model="currentTime"
                                @change="changeCurrentTime"
                                :min="0"
                                :max="totalTime" bar-height="4px" active-color="#ee0a24"/>
                </div>
            </div>
        </div>

        <div class="opt-box">
            <div class="audio">
                <audio autoplay controls :src="src" @timeupdate="updateCurrentTime" @ended="playNext"></audio>
            </div>
            <div class="opt-btn-group">
                <img src="../../assets/main/player/like.png">
                <img :src="getPlayOrderIcon(playOrder)" @click="changePlayOrder">
                <img src="../../assets/main/player/voice.png" @click="showOrHideChangeVoiceBox">
                <img src="../../assets/main/player/list.png" @click="showOrHideNowPlayList">
            </div>
        </div>
    </div>
    <now-play-list v-show="isShowNowPlay" style="z-index: 1"></now-play-list>
    <change-voice-box v-show="isShowChangeVoice" style="z-index: 1"></change-voice-box>
</template>

<script>
import {useStore} from "vuex";
import audioPlayer from "./mainBottom/AudioPlayer.vue";
import nowPlayList from "./mainBottom/nowPlayList.vue";
import changeVoiceBox from "./mainBottom/changeVoiceBox.vue";
import {computed, reactive, ref, watch} from "vue";
import {songApi} from "../../api/songApi.js";
import { ElMessage } from 'element-plus'
export default {
    name: "mainBottomer",
    components:{
        audioPlayer,
        nowPlayList,
        changeVoiceBox
    },
    setup() {
        let store = useStore()
        let src = ref('')
        let songMsg = reactive({
            coverImg:'',
            name:'',
            arts:[]
        })

        let isPlay = computed(()=>store.state.playerStore.isPlay)
        let isShowNowPlay = computed(()=>store.state.playListStore.isShowNowPlayList)
        let isShowChangeVoice = computed(()=>store.state.playListStore.isShowChangeVoice)
        let currentTime = ref(0)
        let totalTime = ref(0)
        let isShowOpen = ref(false)
        let playOrder = computed(()=>store.state.playListStore.playOrder)


        let songId = computed(()=>store.state.playerStore.songId)

        watch(songId,value => {
            store.commit('playerStore/setIsPlay', true)
            getSongSrc(value)
            getSongDetail(value)
        })

        /*
        * 当播放器数值改变时候修改播放时间
        * */
        function updateCurrentTime() {
            currentTime.value = Math.floor(event.target.currentTime)
        }

        /*
        * 得到播放器当前播放音乐的总时间
        * */
        function getTotalTime() {
            setTimeout(()=>{
                let audio = document.getElementsByTagName('audio')[0]
                totalTime.value = Math.floor(audio.duration)
            },500)
        }

        /*
        * 把秒数转化为分钟
        * */
        function secToMin(sec) {
            let m = Math.floor(sec/60) % 60
            let s = sec % 60
            if (m < 10) {
                m = '0' + m
            }
            if (s < 10) {
                s = '0' + s
            }
            return m + ':' + s
        }
        
        /* 
        * 播放或者暂停
        * */
        function playOrPause() {
            let audio = document.getElementsByTagName('audio')[0]
            if (isPlay.value) {
                store.commit('playerStore/setIsPlay', false)
                audio.pause()
            } else {
                store.commit('playerStore/setIsPlay', true)
                audio.play()
            }
        }
        
        /*
        * 根据进度条修改播放时间
        * */
        function changeCurrentTime() {
            let audio = document.getElementsByTagName('audio')[0]
            audio.currentTime = currentTime.value
        }

        /*
        * 展示播放器页面
        * */
        function showPlayer() {
            store.state.playerStore.isShowPlayer = true
        }

        /*
        * 得到播放源地址
        * */
        async function getSongSrc(id) {
            await songApi.songSrc(id,res=>{
                src.value = res.data.data[0].url
                getTotalTime()
            }, reason=>{
                console.warn(reason)
            })
        }

        /*
        * 得到歌曲信息
        * */
        async function getSongDetail(id) {
            await songApi.songDetail(id,res=>{
                songMsg.coverImg = res.data.songs[0].al.picUrl
                songMsg.name = res.data.songs[0].name
                songMsg.arts = res.data.songs[0].ar
            }, reason=>{
                console.warn(reason)
            })
        }

        /*
        * 展示现在播放的歌曲列表
        * */
        function showOrHideNowPlayList() {
            if (isShowNowPlay.value) {
                store.commit('playListStore/setIsShowNowPlayList', false)

            } else {
                store.commit('playListStore/setIsShowNowPlayList', true)
                store.state.playListStore.isShowChangeVoice = false
            }
        }

        /*
        * 展示音量调节列表
        * */
        function showOrHideChangeVoiceBox() {
            if (isShowChangeVoice.value) {
                // store.commit('playListStore/setIsShowNowPlayList', false)
                store.state.playListStore.isShowChangeVoice = false
            } else {
                store.state.playListStore.isShowNowPlayList = false
                store.state.playListStore.isShowChangeVoice = true
            }
        }


        /*
        * 按列表顺序播放下一个音频，参数决定是否进行循环
        * */
        async function nextSongInOrder(isCircle) {
            let nowPlayList = JSON.parse(localStorage.getItem('nowPlayList'))
            let id = ''
            for (let i = 0; i < nowPlayList.length; i++) {
                if (nowPlayList[i].isPlay) {
                    if (i + 1 >= nowPlayList.length) { // 若当前播放的歌曲是列表的最后一首时候
                        if (isCircle) { // 若开启循环播放，则将当前，即最后一位置false，第一首置为true
                            id = nowPlayList[0].id
                            nowPlayList[0].isPlay = true
                            nowPlayList[nowPlayList.length - 1].isPlay = false
                            await getSongSrc(id)
                            await getSongDetail(id)
                            store.commit('playerStore/setSongId', id)
                            break
                        } else { // 若没有循环播放，则按钮失效，只控制台输出
                            ElMessage({
                                message: '当前已为列表中最后一首！',
                                type: 'warning',
                            })
                            break
                        }
                    } else { // 当播放的歌曲不是最后一首的时候，对于顺序播放与训话播放，下一首的操作是一样的
                        id = nowPlayList[i + 1].id
                        nowPlayList[i].isPlay = false
                        nowPlayList[i + 1].isPlay = true
                        await getSongSrc(id)
                        await getSongDetail(id)
                        store.commit('playerStore/setSongId', id)
                        break
                    }
                }
            }
            localStorage.setItem('nowPlayList', JSON.stringify(nowPlayList))
        }


        /*
        * 按列表顺序播放上一个音频，参数决定是否进行循环
        * */
        async function preSongInOrder(isCircle) {
            let nowPlayList = JSON.parse(localStorage.getItem('nowPlayList'))
            let id = ''
            for (let i = 0; i < nowPlayList.length; i++) {
                if (nowPlayList[i].isPlay) {
                    if (i == 0) { // 若当前播放的歌曲是列表的第一一首时候
                        if (isCircle) { // 若开启循环播放，则将当前，即第一首置false，最后一首置为true
                            id = nowPlayList[nowPlayList.length - 1].id
                            nowPlayList[nowPlayList.length - 1].isPlay = true
                            nowPlayList[0].isPlay = false
                            await getSongSrc(id)
                            await getSongDetail(id)
                            store.commit('playerStore/setSongId', id)
                            break
                        } else { // 若没有循环播放，则按钮失效，只控制台输出
                            ElMessage({
                                message: '当前已为列表中第一首！',
                                type: 'warning',
                            })
                            break
                        }
                    } else { // 当播放的歌曲不是最后一首的时候，对于顺序播放与训话播放，下一首的操作是一样的
                        id = nowPlayList[i - 1].id
                        nowPlayList[i].isPlay = false
                        nowPlayList[i - 1].isPlay = true
                        await getSongSrc(id)
                        await getSongDetail(id)
                        store.commit('playerStore/setSongId', id)
                        break
                    }
                }
            }
            localStorage.setItem('nowPlayList', JSON.stringify(nowPlayList))
        }

        /*
        * 从列表中随机选取一首歌进行播放
        * */
        async function randomPlayNext() {
            let nowPlayList = JSON.parse(localStorage.getItem('nowPlayList'))
            let nowIndex = 0
            for (let i = 0; i < nowPlayList.length; i++) {
                if (nowPlayList[i].isPlay) {
                    nowIndex = i
                    break
                }
            }
            let newIndex = Math.floor(Math.random() * nowPlayList.length)
            let id = nowPlayList[newIndex].id
            await getSongSrc(id)
            await getSongDetail(id)
            nowPlayList[newIndex].isPlay = true
            nowPlayList[nowIndex].isPlay = false
            store.commit('playerStore/setSongId', id)
            localStorage.setItem('nowPlayList', JSON.stringify(nowPlayList))
        }


        /*
        * 点击下一首按钮时候的响应事件
        * */
        function playNext() {
            if (playOrder.value == 'order') {
                nextSongInOrder(false)
            } else if (playOrder.value == 'circle') {
                nextSongInOrder(true)
            } else if (playOrder.value == 'random') {
                randomPlayNext()
            } else {
                ElMessage({
                    message: '已设置了单曲循环！',
                    type: 'warning',
                })
            }
        }


        /*
        * 点击上一首按钮时候的响应事件
        * */
        function playPre() {
            if (playOrder.value == 'order') {
                preSongInOrder(false)
            } else if (playOrder.value == 'circle') {
                preSongInOrder(true)
            } else if (playOrder.value == 'random') {
                randomPlayNext()
            } else {
                ElMessage({
                    message: '已设置了单曲循环！',
                    type: 'warning',
                })
            }
        }

        /*
        * 改变播放顺序
        * */
        function changePlayOrder() {
            let nextOrder = ''
            switch (playOrder.value) {
                case 'order':
                    nextOrder = 'circle'
                    ElMessage({
                        message: '已设置为循环播放',
                        type: 'success',
                    })
                    break
                case 'circle':
                    nextOrder = 'single'
                    ElMessage({
                        message: '已设置为单曲循环',
                        type: 'success',
                    })
                    break
                case 'single':
                    nextOrder = 'random'
                    ElMessage({
                        message: '已设置为随机播放',
                        type: 'success',
                    })
                    break
                case 'random':
                    nextOrder = 'order'
                    ElMessage({
                        message: '已设置为顺序播放',
                        type: 'success',
                    })
                    break
            }
            store.commit("playListStore/setPlayOrder", nextOrder)
        }
        // 得到播放顺序图标
        function getPlayOrderIcon(order) {
            return new URL(`../../assets/main/player/order/${order}.png`, import.meta.url).href
        }
        return {
            src,
            songMsg,
            isShowOpen,
            totalTime,
            currentTime,
            isPlay,
            isShowNowPlay,
            isShowChangeVoice,
            playOrder,
            showPlayer,
            updateCurrentTime,
            secToMin,
            playOrPause,
            changeCurrentTime,
            showOrHideNowPlayList,
            showOrHideChangeVoiceBox,
            playNext,
            playPre,
            changePlayOrder,
            getPlayOrderIcon

        }
    }
}
</script>

<style lang="less" scoped>
@import "../../style";

.main-bottomer-container {
    .inner-pos(between);
    width: 100%;
    height: 70px;
    background-color: rgb(52, 51, 50);
    border-top: #000000 solid 1px;
    .cover-img {
        position:relative;
        width: 70px;
        height: 70px;
        img {
            width: 69px;
            height: 69px;
            position: absolute;
        }
    }
}

.player-view {
    .inner-pos(none);
    width: 70%;
    height: 100%;
    .btn {
        padding: 25px 0 25px 0;
        width: 45px;
        height: 45px;
    }

    .slide-box {
        width: calc(100% - 215px);
        height: 100%;
        color: white;

        .msg {
            .inner-pos(between);
            width: 100%;
            height: 50%;
        }

        .slide {
            .inner-pos(none);
            width: 100%;
            height: 40%;
        }
    }
}

.opt-box {
    .inner-pos(around);
    width: 20%;
    height: 100%;
    position: relative;
    .opt-btn-group {
        .inner-pos(around);
        position: absolute;
        width: 100%;
        height: 100%;
        background-color: #343332;
        img {
            width: 20px;
            height: 20px;
        }
    }

    .audio {
        position: absolute;
        width: 100%;
        height: 100%;
    }
}


</style>